package com.bestillet.kyllingogco;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.AsyncTask.Status;
import android.util.Log;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class CheckoutActivity extends Activity {
	private ArrayList<String> earliest, latest;
	private ArrayList<Card> cards;
	
	private SharedPreferences preferences;
	private EditText name, cellphone, message;
	private CheckBox student;
	private Spinner early, late;
	private Context context;
	private Button submit, back, home;
	
	private ShopApplication app;
	private LoadingDialog loading;
	private BasketTask task;
	private Shop shop;
	
	private boolean copied;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.checkout);
		
		context = this;
		copied = getIntent().getBooleanExtra("copied", false);
		
		preferences = getSharedPreferences("Kylling & Co", MODE_PRIVATE);

		app = (ShopApplication) getApplicationContext();
		cards = app.getCards();
		shop = app.getShop();
		
		student = (CheckBox) findViewById(R.id.chkStudentCard);
		message = (EditText) findViewById(R.id.txtMessage);
		
		name = (EditText) findViewById(R.id.txtName);
		name.setText(preferences.getString("name", ""));
		
		cellphone = (EditText) findViewById(R.id.txtCellphone);
		cellphone.setText(preferences.getString("phone", ""));
		
		back = (Button) findViewById(R.id.btnCheckoutBack);
		back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		home = (Button) findViewById(R.id.btnCheckoutHome);
		home.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (copied) {
					finish();
				} else {
					Intent intent = new Intent(v.getContext(), CategoryActivity.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);
				}
			}
		});
		
		submit = (Button) findViewById(R.id.btnSubmit);
		submit.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (shop.getHours().equals("Lukket") || shop.getOrders().equals("Lukket")) {
					Toast.makeText(v.getContext(), R.string.error_closed, Toast.LENGTH_LONG).show();
					return;
				}
				try {
					if (early.getSelectedItemPosition() == 0) {
						Toast.makeText(v.getContext(), R.string.error_checkout_early, Toast.LENGTH_LONG).show();
						return;
					}
					if (late.getSelectedItemPosition() == 0) {
						Toast.makeText(v.getContext(), R.string.error_checkout_late, Toast.LENGTH_LONG).show();
						return;
					}

					String n = name.getText().toString();
					String c = cellphone.getText().toString();
					
					if (n.length() == 0) {
						Toast.makeText(v.getContext(), R.string.error_checkout_name, Toast.LENGTH_LONG).show();
						return;
					}
					if (c.length() == 0) {
						Toast.makeText(v.getContext(), R.string.error_checkout_cellphone, Toast.LENGTH_LONG).show();
						return;
					}
					if (c.length() != 8) {
						Toast.makeText(v.getContext(), R.string.error_checkout_cellphone_digits, Toast.LENGTH_LONG).show();
						return;
					}
					
					Calendar calendar = Calendar.getInstance();
					calendar.add(Calendar.MINUTE, 5);
					String t = (String)(early.getSelectedItem());
					float now = calendar.getTimeInMillis();
					calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(t.split(":")[0]));
					calendar.set(Calendar.MINUTE, Integer.parseInt(t.split(":")[1]));
					
					if (calendar.getTimeInMillis() - now < 0) {
						Toast.makeText(v.getContext(), R.string.error_checkout_deadline, Toast.LENGTH_LONG).show();
						setTimes();
						return;
					}

					loading = new LoadingDialog(v.getContext());
					loading.show();
					task = new BasketTask();
					task.execute();
				} catch (NumberFormatException e) {
					Toast.makeText(v.getContext(), R.string.error_time, Toast.LENGTH_LONG).show();
				}
			}
		});

		late = (Spinner) findViewById(R.id.late);
		late.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				v.performClick();
				View focus = getCurrentFocus();
				if (focus != null) {
					InputMethodManager manager = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
					manager.hideSoftInputFromWindow(focus.getWindowToken(), 0);
				}
				return false;
			}
		});
		
		early = (Spinner) findViewById(R.id.early);
		early.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				v.performClick();
				View focus = getCurrentFocus();
				if (focus != null) {
					InputMethodManager manager = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
					manager.hideSoftInputFromWindow(focus.getWindowToken(), 0);
				}
				return false;
			}
		});
		early.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
				latest = new ArrayList<String>();
				latest.add(getResources().getString(R.string.checkout_latest));
				for (int i = position; i < earliest.size(); i++)
					if (i > 0)
						latest.add(earliest.get(i));
				ArrayAdapter<String> adapter = new ArrayAdapter<String>(parent.getContext(), android.R.layout.simple_spinner_item, latest);
				adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				late.setAdapter(adapter);
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				latest = new ArrayList<String>();
				latest.add(getResources().getString(R.string.checkout_latest));
				ArrayAdapter<String> adapter = new ArrayAdapter<String>(parent.getContext(), android.R.layout.simple_spinner_item, latest);
				adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				late.setAdapter(adapter);
			}
		});
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		
		if (task != null)
			if (task.getStatus() == Status.RUNNING)
				task.cancel(true);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		if (shop.getHours().equals("Lukket") || shop.getOrders().equals("Lukket")) {
			Toast.makeText(this, R.string.error_closed, Toast.LENGTH_LONG).show();
			finish();
		} else {
			setTimes();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(android.view.Menu menu) {
		menu.add(android.view.Menu.NONE, -2, 0, "Info");
		menu.add(android.view.Menu.NONE, -1, 0, "Indstillinger");
		menu.add(android.view.Menu.NONE, 0, 0, "Tidligere ordrer");
		for (int i = 0; i < cards.size(); i++)
			menu.add(android.view.Menu.NONE, cards.get(i).getIdx(), cards.get(i).getPosition() + 1, cards.get(i).getName());
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case -2:
			Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://m.kyllingogco.dk/kontakt.asp?shopid=" + app.getShop().getIdx()));
			startActivity(browserIntent);
			break;
		case -1:
			Intent customer = new Intent(this, CustomerActivity.class);
			startActivity(customer);
			break;
		case 0:
			Intent order = new Intent(this, OrderActivity.class);
			startActivity(order);
			break;
		default:
			Intent card = new Intent(this, CardActivity.class);
			card.putExtra("idx", item.getItemId());
			card.putExtra("title", item.getTitle());
			startActivity(card);
			break;
		}
    	return true;
	}
	
	public void setTimes() {
		Calendar start = Calendar.getInstance();
		start.add(Calendar.MINUTE, 10);
		int hour = Integer.parseInt(app.getShop().getHours().split("-")[0].split(":")[0]);
		int minute = Integer.parseInt(app.getShop().getHours().split("-")[0].split(":")[1]);
		if (start.get(Calendar.HOUR_OF_DAY) >= hour) {
			hour = start.get(Calendar.HOUR_OF_DAY);
			minute = 5 * (Math.round(start.get(Calendar.MINUTE) / 5));
		}
		start.set(Calendar.HOUR_OF_DAY, hour);
		start.set(Calendar.MINUTE, minute);
		
		Calendar end = (Calendar) start.clone();
		end.set(Calendar.HOUR_OF_DAY, Integer.parseInt(app.getShop().getHours().split("-")[1].split(":")[0]));
		end.set(Calendar.MINUTE, Integer.parseInt(app.getShop().getHours().split("-")[1].split(":")[1]));
		
		earliest = new ArrayList<String>();
		earliest.add(getResources().getString(R.string.checkout_early));
		
		if (start.getTimeInMillis() >= end.getTimeInMillis())
			end.add(Calendar.DAY_OF_MONTH, 1);
		
		while (start.getTimeInMillis() <= end.getTimeInMillis()) {
			hour = start.get(Calendar.HOUR_OF_DAY);
			minute = start.get(Calendar.MINUTE);
			earliest.add(hour + ":" + (minute < 10 ? "0" : "") + minute);
			start.add(Calendar.MINUTE, 5);
		}
		
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, earliest);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		early.setAdapter(adapter);
	}
	
	private class BasketTask extends AsyncTask<Void, Void, Boolean> {
		private int orderId;
		
    	@Override
		protected Boolean doInBackground(Void... params) {
    		String n = name.getText().toString();
    		String p = cellphone.getText().toString();
    		String m = (message.getText().length() > 0 ? message.getText().toString() : "Ingen besked");
    		String d = (String) early.getSelectedItem();
    		String l = (String) late.getSelectedItem();
    		try {
				InputStream in = Server.post(Server.ORDER, Server.getOrderXml(n, p, m, d, l, app.getShop().getIdx(), app.getBasketId(), (student.isChecked() ? 1 : 0)));
				XmlPullParser parser = Server.toXmlParser(in);
				orderId = XmlParser.getOrderId(parser);
			} catch (IOException e) {
				Log.e("Shop", "IOException: " + e.getMessage());
				return false;
			} catch (XmlPullParserException e) {
				Log.e("Shop", "XmlPullParserException: " + e.getMessage());
				return false;
			} catch (NullPointerException e) {
				Log.e("Shop", "NullPointerException: " + e.getMessage());
				return false;
			} catch (IllegalArgumentException e) {
				Log.e("Shop", "IllegalArgumentException: " + e.getMessage());
				return false;
			}
    		return true;
    	}
    	
    	@Override
	    protected void onPostExecute(Boolean success) {
	    	if (success) {
	    		Intent intent = new Intent(context, StatusActivity.class);
	    		intent.putExtra("orderId", orderId);
	    		intent.putExtra("student", student.isChecked());
	    		startActivity(intent);
	    	} else {
	    		AlertDialog.Builder builder = new AlertDialog.Builder(context);
	    		builder.setMessage(R.string.error_send_order)
	    		       .setTitle(R.string.error)
	    		       .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								task = new BasketTask();
								task.execute();
								loading.show();
							}
						})
						.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								finish();
							}
						});
	    		AlertDialog dialog = builder.create();
	    		dialog.show();
	    	}
	    	loading.dismiss();
    	}
	}
}